package com.example.micro_property_springboot.controller;

import com.example.micro_property_springboot.entity.BackupStatistics;
import com.example.micro_property_springboot.entity.SysBackupRecord;
import com.example.micro_property_springboot.service.SysBackupRecordService;
import com.example.micro_property_springboot.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * 系统备份记录控制器
 * 提供数据库备份相关的REST API接口
 */
@RestController
@RequestMapping("/api/system/backup")
public class SysBackupRecordController {
    
    @Autowired
    private SysBackupRecordService backupRecordService;
    
    /**
     * 执行手动数据库备份
     */
    @PostMapping("/manual")
    public ResponseEntity<SysBackupRecord> doManualBackup(@RequestParam(required = false) String remark) throws IOException {
        Long userId = SecurityUtils.getCurrentUserId();
        if (remark == null) {
            remark = "手动备份操作";
        }
        
        SysBackupRecord record = backupRecordService.doManualBackup(userId, remark);
        return ResponseEntity.ok(record);
    }
    
    /**
     * 恢复数据库备份
     */
    @PostMapping("/{backupId}/restore")
    public ResponseEntity<Boolean> restoreFromBackup(@PathVariable Long backupId) throws IOException {
        boolean success = backupRecordService.restoreFromBackup(backupId);
        return ResponseEntity.ok(success);
    }
    
    /**
     * 获取最近的备份记录
     */
    @GetMapping("/recent")
    public ResponseEntity<List<SysBackupRecord>> getRecentBackupRecords(@RequestParam(defaultValue = "10") Integer limit) {
        List<SysBackupRecord> records = backupRecordService.getRecentBackupRecords(limit);
        return ResponseEntity.ok(records);
    }
    
    /**
     * 删除备份记录
     */
    @DeleteMapping("/{backupId}")
    public ResponseEntity<Boolean> deleteBackup(@PathVariable Long backupId) {
        boolean success = backupRecordService.deleteBackup(backupId);
        return ResponseEntity.ok(success);
    }
    
    /**
     * 清理过期备份
     */
    @PostMapping("/clean-expired")
    public ResponseEntity<Boolean> cleanExpiredBackups(@RequestParam(defaultValue = "30") Integer keepDays) {
        backupRecordService.cleanExpiredBackups(keepDays);
        return ResponseEntity.ok(true);
    }
    
    /**
     * 获取备份统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<BackupStatistics> getBackupStatistics() {
        BackupStatistics statistics = backupRecordService.getBackupStatistics();
        return ResponseEntity.ok(statistics);
    }
}